<script lang="ts" setup>
import { ref } from 'vue';
import { useFetch } from '@/home/hooks/fetch';
import { useAppStore } from '@/home/stores/app';

const appStore = useAppStore();

const props = defineProps({
  name: {
    type: String,
    default: '',
  },
  email: {
    type: String,
    default: '',
  },
});

const { $fetch } = useFetch();
// 判断用户是否退订成功
const cancelled = ref(false);
// 是否重新订阅
const isResubscribe = ref(false);

// 重新订阅
const resubscribe = async () => {
  const { isSuccess } = await $fetch('/email/subscribeEmail', {
    method: 'post',
    data: {
      userName: props.name,
      emailAddress: props.email,
    },
  });

  if (isSuccess) {
    isResubscribe.value = true;
  }
}

// 退订
const cancelSubscribe = async () => {
  const { isSuccess } = await $fetch('/email/unsubscribeEmail', {
    method: 'post',
    data: {
      userName: props.name,
      emailAddress: props.email,
    },
  });

  if (isSuccess) {
    cancelled.value = true;
  }
}
</script>

<template>
  <main class="flex-x-center text-hex-292929">
    <section class="mx-auto my-208 w-500 rounded-6 bg-white p-40" v-if="!cancelled">
      <h2 class="text-center text-24 font-medium leading-34">{{ $t('home.subscription.unsubscribe.title') }}</h2>
      <p class="mt-24 text-16 leading-24">{{ appStore.config.name }}:</p>
      <p class="mt-24 text-16 leading-24">
        {{ $t('home.subscription.unsubscribe.content', { email: props.email, title: appStore.config.name }) }}
      </p>
      <button type="button" class="mt-40 block h-48 w-full rounded-6 bg-primary-1 text-16 text-white" @click="cancelSubscribe">{{ $t('home.subscription.unsubscribe.button') }}</button>
    </section>

    <section class="mx-auto my-208 w-500" v-else>
      <div class="text-center">
        <span class="i-icons:success inline-block size-88 text-primary-1"></span>
      </div>
      <h2 class="mt-16 w-full text-center text-24 text-primary-1 font-medium leading-34">{{ isResubscribe ? $t('home.subscription.subscribe.success.title') : $t('home.subscription.unsubscribe.success.title') }}</h2>
      <template v-if="!isResubscribe">
        <p class="mt-32 text-16 leading-24">{{ appStore.config.name }}:</p>
        <i18n-t keypath="home.subscription.unsubscribe.success.content" scope="global" tag="p" class="mt-24 indent-2em text-16 leading-24">
          <template #resubscribe>
            <a href="javascript:;" @click="resubscribe" class="text-primary-1">{{ $t('home.subscription.unsubscribe.resubscribe') }}</a>
          </template>
        </i18n-t>
        <p class="mt-24 indent-2em text-16 leading-24">{{ $t('home.subscription.unsubscribe.thanks') }}！</p>
      </template>
    </section>
  </main>
</template>

<style lang="scss" scoped>
</style>
